/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Worklog.java
 *
 * Created on Jul 14, 2011, 1:10:45 PM
 */
package javadatabasegui;


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import java.util.*;
import java.text.*;

/**
 *
 * @author Paul Laptop
 */
public class TimeTracking extends javax.swing.JFrame {
    Connection con;
    String userEmail;
    int projectID;
    String mName;
    String tName;
    Date dueDate;

    /** Creates new form Worklog */
    public TimeTracking(Connection conn, String uEmail, int pid, String msName, String tsName, Date dDate){
        con = conn;
        userEmail = uEmail;
        projectID = pid;
        mName = msName;
        tName = tsName;
        dueDate = dDate;
        initComponents();
    }

    private String TaskDesc(){
        ResultSet rs = null;
        String TDesc = null;
      try{
            Statement stmt = con.createStatement();
            if (stmt.execute("SELECT T_Desc FROM Tasks WHERE PID = \""+ projectID +"\" AND M_Name = \""+ mName +"\" AND T_Name = \""+ tName +"\""))
                rs = stmt.getResultSet();
                rs.next(); 
                TDesc = rs.getString("T_Desc");
        }catch(SQLException e){
            System.err.println("Error in Project Count");
            System.err.println(e.getMessage());
        }
 
        return TDesc;
      }
    
    private String EmpName(){
        String Uname = null;
        try{
            Statement stmt = con.createStatement();
            ResultSet rs = null;
            if (stmt.execute("SELECT F_Name,L_Name FROM " + "cs4400_Group_14.Users WHERE Users.Email =\"" + userEmail + "\"")){
                rs = stmt.getResultSet();
            }
            rs.next();
            Uname = rs.getString("F_Name") + " " + rs.getString("L_Name");
        }catch(SQLException e){
            System.err.println(e.getMessage());
            System.err.println(e.getSQLState());
        }
        return Uname;
    }

    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        typeDate = new javax.swing.JTextField();
        typeHours = new javax.swing.JTextField();
        saveButton = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18));
        jLabel1.setText("Time Tracking");

        jLabel2.setText("Milestone");

        jLabel3.setText("Task");

        jLabel4.setText("Description");

        jLabel6.setText("Employee");

        jLabel7.setText("Date");

        jLabel8.setText("Hours");

        jTextArea1.setColumns(20);
        jTextArea1.setEditable(false);
        jTextArea1.setRows(5);
        jTextArea1.setText(TaskDesc());
        jScrollPane1.setViewportView(jTextArea1);

        typeDate.setText("yyyy-mm-dd");

        saveButton.setText("Save");
        saveButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                saveButtonMouseClicked(evt);
            }
        });

        jLabel5.setText(mName);

        jLabel9.setText(tName);

        jLabel10.setText(EmpName());

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(jLabel6)
                            .addComponent(jLabel7)
                            .addComponent(jLabel8))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
                            .addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
                            .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
                            .addComponent(typeHours, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
                            .addComponent(typeDate, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE))))
                .addGap(50, 50, 50))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(449, Short.MAX_VALUE)
                .addComponent(saveButton)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGap(13, 13, 13)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel9))
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(90, 90, 90)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(jLabel10))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel7)
                            .addComponent(typeDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel8)
                            .addComponent(typeHours, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                .addComponent(saveButton)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        new UserDashboard(userEmail, con).setVisible(true);
                this.dispose();
    }//GEN-LAST:event_formWindowClosing

    private void saveButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveButtonMouseClicked
        // TODO add your handling code here:
        String thisDate = typeDate.getText();
        String thisHours = typeHours.getText();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date Dt = null;
        try {
            Dt = sdf.parse(thisDate);
        }catch (ParseException e){ 
            JOptionPane.showMessageDialog(null, "Invalid Date Format.");
            return;
        }
        if (!sdf.format(Dt).equals(thisDate)) {
            JOptionPane.showMessageDialog(null, "Invalid Date Format.");
            return;
        }
        if (Float.parseFloat(thisHours) > 8){
          JOptionPane.showMessageDialog(null, "You cannot work on one task more than 8 hours a day!");
          return;
        }
        
        Calendar cal = Calendar.getInstance();
        Calendar currentcal = Calendar.getInstance();
        SimpleDateFormat temp1 = new SimpleDateFormat();
        temp1.applyPattern("yyyy-MM-dd");
        Date processDate = null;
        try {
            processDate = temp1.parse(thisDate);
        } catch (ParseException ex) {
            Logger.getLogger(TimeTracking.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        //if(cal.after(currentcal))
        //System.out.print("Current date(" + new SimpleDateFormat("MM/dd/yyyy").format(currentcal.getTime()) + ") is less than the given date " + new SimpleDateFormat("MM/dd/yyyy").format(cal.getTime()));

        Boolean emptySet = false;
        cal.setTime(processDate);
        String origcal = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        if(cal.after(currentcal)){
         JOptionPane.showMessageDialog(null, "Date cannot be later than today!");
         return;
        }else{
             ResultSet rs = null;
          try{                     
            Statement stmt = con.createStatement();
            if (stmt.execute("SELECT * FROM `cs4400_Group_14`.`Worklog` WHERE PID = \"" + projectID + "\" AND M_Name = \"" + mName + "\" AND T_Name = \"" + tName + "\" AND Date = \"" + origcal + "\""))
              rs = stmt.getResultSet();
              if(rs.next() == false)
                  emptySet = true;
          }
          catch(SQLException e){
                    System.err.println("Error trying to get worklog");
                    System.err.println(e.getMessage());
                }
          
          if(emptySet == true){
             try{
                    //Update the new worklog to the database
                    Statement stmt1 = con.createStatement();
                    System.out.println(origcal);
                    stmt1.execute("INSERT INTO `cs4400_Group_14`.`Worklog` (`PID`, `M_Name`, `T_Name`, `Date`, `Hours`) VALUES ('" + projectID + "', '" + mName + "', '"+ tName +"', '"+ origcal +"', '"+ thisHours +"')");
                }catch(SQLException e){
                    System.err.println("Error trying to insert data");
                    System.err.println(e.getMessage());
                }
          }else{
              Float haveHours = null;
                try {
                    haveHours = rs.getFloat("Hours");
                } catch (SQLException ex) {
                    Logger.getLogger(TimeTracking.class.getName()).log(Level.SEVERE, null, ex);
                }
                if( (haveHours + Float.parseFloat(thisHours)) > 8){
                   JOptionPane.showMessageDialog(null, "You cannot work on one task more than 8 hours a day!");
                   return;
                }else{
                  try{
                    //Update the new project to the database
                    Statement stmt = con.createStatement();
                    Double totHours = haveHours + Double.parseDouble(thisHours);                    
                    stmt.execute("UPDATE `cs4400_Group_14`.`Worklog` SET `Hours` = '" + totHours + "' WHERE PID = \"" + projectID + "\" AND M_Name = \"" + mName + "\" AND T_Name = \"" + tName + "\" AND Date = \"" + origcal + "\"");
                }catch(SQLException e){
                    System.err.println("Error trying to update the project");
                    System.err.println(e.getMessage());
                }
                }
          }
          
          JOptionPane.showMessageDialog(null, "Save!");
          new UserDashboard(userEmail, con).setVisible(true);
          this.dispose();
        }
        
        
    }//GEN-LAST:event_saveButtonMouseClicked

    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JButton saveButton;
    private javax.swing.JTextField typeDate;
    private javax.swing.JTextField typeHours;
    // End of variables declaration//GEN-END:variables
}
